package com.thti.mecool.client.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.thti.mecool.client.activity.LoadingDialog.getDataOK;
import com.thti.mecool.client.adapter.GridViewAdapter;
import com.thti.mecool.client.base.BaseActivity;
import com.thti.mecool.client.base.Cache;
import com.thti.mecool.client.model.biz.MessagesBizImpl;
import com.thti.mecool.client.model.biz.PlanBizImpl;
import com.thti.mecool.client.model.po.MobileMessages;
import com.thti.mecool.client.service.LocateService;
import com.thti.mecool.client.service.NotificationService;
import com.thti.mecool.client.util.TimeUtil;
import com.thti.mecool.client.util.Util;

public class HomeActivity extends BaseActivity {
    /**
     * Called when the activity is first created.
     */
    private GridView mecool_gridView;
    LoadingDialog loadingDialog;
    ActivityManager am;
    TextView mecool_name;
    GridViewAdapter adapter;
    private PlanBizImpl planBizImpl;
    private int msgNum;
    List<MobileMessages> list;
    public  boolean okFlag=false;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        menu.add(0, 1, 0, "设置");
        menu.add(0, 2, 0, "刷新数据");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
//            case 1:
//                Intent i = new Intent(this, SettingActivity.class);
//                startActivity(i);
//                break;
            case 2:
                loadingDialog.show();
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        noTitle();
        setContentView(R.layout.mecool_home);
        Cache.add(this);
        planBizImpl = new PlanBizImpl(this);
        planBizImpl.deletePlanForDate(TimeUtil.DateConvert(getCurrentUser().getCurrentServerTime(), 4));
        Toast.makeText(
                this,
                "用户 " + getCurrentUser().getLoginName() + " ,您好！您的ID为"
                        + getCurrentUser().getId(), 4000).show();
        am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

        Intent in = new Intent(this, LocateService.class);
        startService(in);
        Intent intentNotification = new Intent(this, NotificationService.class);
        startService(intentNotification);

        mecool_name = (TextView) findViewById(R.id.mecool_name);

        mecool_name = (TextView) findViewById(R.id.mecool_name);
        mecool_name.setText(getCurrentUser().getDisplayName());
        mecool_gridView = (GridView) findViewById(R.id.mecool_gridView);
        MessagesBizImpl messagesBizImpl = new MessagesBizImpl(this);
        list = new ArrayList<MobileMessages>();
        list.addAll(messagesBizImpl.findUnReadAllMsg());
        msgNum = list.size();
        planBizImpl.deletePlanForDate(TimeUtil.dateToString(new Date(), 4));

        adapter = new GridViewAdapter(this).setMsgNum(msgNum);
        mecool_gridView.setAdapter(adapter);
        mecool_gridView.setCacheColorHint(-000000);
        mecool_gridView
                .setOnItemClickListener(new GridView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                        Intent intent = new Intent();
                        switch (Integer.parseInt(arg1.getTag().toString())) {

                            case 0:
                                intent.setClass(HomeActivity.this,
                                        TaskActivity.class);
                                startActivity(intent);
                                break;
                            case 1:
                                intent.setClass(HomeActivity.this,
                                        PlanActivity.class);
                                startActivity(intent);
                                break;
                            case 2:
                                intent.setClass(HomeActivity.this,
                                        CommunicationActivity.class);
                                startActivity(intent);
                                break;
                            case 3:
                                intent.setClass(HomeActivity.this,
                                        WorkMemoActivity.class);
                                startActivity(intent);
                                break;
                            case 4:
                                intent.setClass(HomeActivity.this,
                                        UserCenterActivity.class);
                                startActivity(intent);
                                break;
                            case 5:
                                intent.setClass(HomeActivity.this,
//									ShowSalersActivity.class);
                                        SellAndReceiptActivity.class);
                                startActivity(intent);
                                // dialog();
                                break;
                            case 6:
                                dialog();
//							intent.setClass(HomeActivity.this, SaleVolumeActivity.class);
//							startActivity(intent);
                                break;
//						case 7:
//							dialog();
////							intent.setClass(HomeActivity.this, SellAndReceiptActivity.class);
////							startActivity(intent);
//							// intent.setClass(HomeActivity.this,
//							// SaleVolumeActivity.class);
//							// startActivity(intent);
//							break;

                            // case 7:
                            // intent.setClass(HomeActivity.this,
                            // SellAndReceiptActivity.class);
                            // startActivity(intent);

                        }
                    }
                });
        loadingDialog = new LoadingDialog(this, R.style.dialog);
        loadingDialog.setIsOKListener(gDataOK);
        if (true) {
            loadingDialog.show();
        }
    }

    Handler h=new Handler(){
    	@Override
		public void handleMessage(android.os.Message msg) {
    		switch (msg.what) {
			case 10:
				adapter.notifyDataSetChanged();
				break;
			}
    	};
    };
    
    /**
     * 返回按钮退出
     */
    private static Boolean isExit = false;
    private static Boolean hasTask = false;
    Timer tExit = new Timer();
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            isExit = false;
            hasTask = true;
        }
    };
	getDataOK gDataOK=new getDataOK() {
		
		@Override
		public void getDataOK(boolean isOK) {
			if(isOK){
				HomeActivity.this.okFlag=true;
				h.sendEmptyMessage(10);}
		}
	};

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
	if (isExit == false) {
        isExit = true;
        Util.sendToast(this, "再按一次后退键退出应用程序");
        if (!hasTask) {
            tExit.schedule(task, 2000);
        }
    } else {
        BaseActivity.exitApp();
        System.exit(0);
        am.restartPackage(this.getPackageName());
        this.finish();
    }
    return false;
case KeyEvent.KEYCODE_MENU:
	if(okFlag){
		Util.sendToast(HomeActivity.this, "最近已经更新过数据，请查看后再更新！");
		return true;
		}else{
			return super.onKeyDown(keyCode, event);
		}
default:
}
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        okFlag=false;
        MessagesBizImpl messagesBizImpl = new MessagesBizImpl(this);
        list.clear();
        list.addAll(messagesBizImpl.findUnReadAllMsg());
        if(adapter!=null){
        adapter.setMsgNum(list.size());
        adapter.notifyDataSetChanged();
        }
    }



}